package com.learn.thread;

import java.util.Objects;

/**
 * 龟兔赛跑
 */
public class Race implements Runnable {

    private String winner;

    @Override
    public void run() {
        for (int i = 0; i <= 100; i++) {
            if(getWinner(i, Thread.currentThread().getName())){
                return;
            }
            if(Objects.equals("兔子",Thread.currentThread().getName())&&i==50){
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            System.out.println(Thread.currentThread().getName() + "----跑了第---->" + i + "步数");
        }
    }

    private Boolean getWinner(int step, String currentThreadName) {
        if (Objects.nonNull(winner)) {
            System.out.println("winner is " + winner);
            return true;
        }
        if (step == 100) {
            winner = currentThreadName;
            System.out.println("winner is " + winner);
            return true;
        }
        return false;
    }

    public static void main(String[] args) {
        Race race = new Race();
        new Thread(race, "兔子").start();
        new Thread(race, "乌龟").start();
    }
}
